package com.cuz.hot100;

import java.util.*;

public class Q56mergeInterval {
    public static int[][] merge1(int[][] intervals) {
        if (intervals == null || intervals.length == 0 || intervals[0].length == 0) {
            return intervals;
        }
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        LinkedList<int[]> res = new LinkedList<>();
        res.addLast(intervals[0]);
        for (int index = 1; index < intervals.length; index++) {
            int[] curArray = intervals[index];
            int curMin = curArray[0];
            int[] lastArray = res.getLast();
            int lastMax = lastArray[1];
            if (lastMax >= curMin) {
                lastArray[1] = Math.max(curArray[1], lastArray[1]);
            } else {
                res.addLast(curArray);
            }
        }
        return res.toArray(new int[res.size()][2]);
    }
}
